package com.lan.iot;


import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lan.iot.AirCdn;
import com.lan.iot.Music;
import com.lan.iot.R;
import com.lan.iot.light;
import com.lan.iot.utils.JsonUtil;
import com.lan.iot.utils.OkHttpRequestUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;
import okhttp3.Response;
import okhttp3.ResponseBody;

import static com.lan.iot.Activity_index.numMap;
import static com.lan.iot.Add.DEV_COUNT;

/**
 * Created by Eve on 2022/10/19.
 */
public class RAdapterdev extends RecyclerView.Adapter {
    private List<String> nData = new ArrayList<>();
    private List<Integer> imgData = new ArrayList<>();
    private List<Class> intentClass = new ArrayList<>();
    private List<Boolean> haveLo = new ArrayList<>();
    private Context context;
    public int f = 0;

    private int[] imgid = {R.drawable.acd, R.drawable.lock_200, R.drawable.light_200, R.drawable.chuanglain200, R.drawable.fenwei};

    public void boasend(int po, boolean b) {
        switch (po) {
            case 2:
//            Intent intent2 = new Intent("android.intent.action.CART_BROADCAST_a_2z");
//            intent2.putExtra("zdata", b);
//            LocalBroadcastManager.getInstance(context).sendBroadcast(intent2);
//            context.sendBroadcast(intent2);
//            Intent intent3 = new Intent("android.intent.action.CART_BROADCAST_a_3z");
//            intent3.putExtra("zdata", b);
//            LocalBroadcastManager.getInstance(context).sendBroadcast(intent3);
//            context.sendBroadcast(intent3);
                Intent intent1 = new Intent("android.intent.action.CART_BROADCAST");
                intent1.putExtra("data", b);
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent1);
                context.sendBroadcast(intent1);
                break;
            case 0:
//            Intent intent22 = new Intent("android.intent.action.CART_BROADCAST_a_2");
//            intent22.putExtra("acdndata", b);
//            LocalBroadcastManager.getInstance(context).sendBroadcast(intent22);
//            context.sendBroadcast(intent22);
//            Intent intent32 = new Intent("android.intent.action.CART_BROADCAST_a_3");
//            intent32.putExtra("acdndata", b);
//            LocalBroadcastManager.getInstance(context).sendBroadcast(intent32);
//            context.sendBroadcast(intent32);
                Intent intent12 = new Intent("android.intent.action.CART_BROADCAST_a");
                intent12.putExtra("acdndata", b);
                intent12.putExtra("isall", true);

                LocalBroadcastManager.getInstance(context).sendBroadcast(intent12);
                context.sendBroadcast(intent12);
                break;
            case 3:
//            Intent intent33 = new Intent("android.intent.action.CART_BROADCAST_a_3c");
//            intent33.putExtra("cdata", b);
//            LocalBroadcastManager.getInstance(context).sendBroadcast(intent33);
//            context.sendBroadcast(intent33);
//            Intent intent23 = new Intent("android.intent.action.CART_BROADCAST_a_2c");
//            intent23.putExtra("cdata", b);
//            LocalBroadcastManager.getInstance(context).sendBroadcast(intent23);
//            context.sendBroadcast(intent23);

                Intent intent13 = new Intent("android.intent.action.CART_BROADCAST_c");
                intent13.putExtra("cdata", b);
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent13);
                context.sendBroadcast(intent13);
                break;
            case 1:
                Intent intent24 = new Intent("android.intent.action.CART_BROADCAST_door");
                intent24.putExtra("mdata", b);
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent24);
                context.sendBroadcast(intent24);
            case 4:
                Intent intent25 = new Intent("android.intent.action.CART_BROADCAST_fenwei");
                intent25.putExtra("acdndata", b);
                intent25.putExtra("isall", true);
                LocalBroadcastManager.getInstance(context).sendBroadcast(intent25);
                context.sendBroadcast(intent25);
            default:
                ;
        }
    }
    private void init() {
        NetWorkBusiness netWorkBusiness2 = new NetWorkBusiness("", "http://www.nlecloud.com/");
        netWorkBusiness2.signIn(new SignIn("17680316790", "1234567890"), new NCallBack<BaseResponseEntity<User>>(context) {
            @Override
            protected void onResponse(BaseResponseEntity<User> response) {
                netWorkBusiness = new NetWorkBusiness(response.getResultObj().getAccessToken(), "http://www.nlecloud.com/");
                token = response.getResultObj().getAccessToken();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        NlecloudUtil nlecloudUtil=new NlecloudUtil();
//                        nlecloudUtil.gainDevices("596248", token, new NlecloudResponse<List<SensorInfoEntity>>() {
//                            @Override
//                            public void callBack(ResultEntity<List<SensorInfoEntity>> resultEntity) {
//                                List<SensorInfoEntity> resultObj = resultEntity.getResultObj();
//                            }
//                        });
                    }
                }).start();
            }
        });
    }
    public void on() {
        f = 1;
        notifyDataSetChanged();
    }
    String token;
    NetWorkBusiness netWorkBusiness;
    private void controlDevice(String deviceId, String apiTag, String data) {
        System.out.println("6");
        //发出网络请求
        String SENSOR_DATA_ALL = "http://api.nlecloud.com/Cmds";
        try {
            Map<String, String> valmap = new HashMap<>();
            valmap.put("deviceId", deviceId);
            valmap.put("apiTag", apiTag);
            Response access = OkHttpRequestUtil.postAccess(SENSOR_DATA_ALL, valmap, data, token);
            if (access.isSuccessful()) {
                ResponseBody body = access.body();
                Map map = JsonUtil.toMap(body.string());
                Double status = (double) map.get("Status");
                Message message = new Message();
                if (status == null || status.intValue() != 0.0) {
                    message.arg1 = 0;
                } else {
                    message.arg1 = 1;
                }
                message.obj = map.get("Msg");
                message.what = 0x01;
                handler.sendMessage(message);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0x01:
                    int status = msg.arg1;
                    String msgText = "";
                    if (status == 0) {
                        msgText = "控制失败:" + msg.obj;
                    } else if (status == 1) {
                        msgText = "控制成功:" + msg.obj;
                    }
                    Toast.makeText(context, msgText, Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
    public void off() {
        f = 2;
        notifyDataSetChanged();
    }
    String tag[]={"Kyijian","Myijian","Dyijian","Cyijian","Fyijian"};
public List<Integer> typelist=new ArrayList<>();
    public RAdapterdev(Context context) {
        this.context = context;
        SharedPreferences settings = context.getSharedPreferences(DEV_COUNT, Context.MODE_PRIVATE);
        int devcount = settings.getInt("devcount", 0);
        for (int i = 1; i <= devcount; i++) {
            if(typelist.contains(settings.getInt("devtype" + i, -1))){

            }else {
                typelist.add(settings.getInt("devtype" + i, -1));
            imgData.add(settings.getInt("devtype" + i, -1));
            nData.add(settings.getString("devname" + i, "未命名设备"));}
        }
        //item中的数据
//        mData.add("客户联系");
//        mData.add("客户群");
//        mData.add("微信客服");
//        mData.add("离职继承");
//        mData.add("群发助手");
//        mData.add("对外收款");

//        haveLo.add(true);

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        int layoutId;
        //加载item的布局文件
        layoutId = R.layout.item_one_view_layout;
        view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        init();
        return new VH(view);
    }
//                if(settings.getInt("devtype"+i,-1)==0||settings.getInt("devtype"+i,-1)==4)haveLo.add(true);else haveLo.add(false);
    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        final VH vh = (VH) holder;
        switch (f) {
            case 0:
                break;
            case 1:
                if (imgData.get(position)!=1&&imgData.get(position)!=3)
                    vh.aSwitch.setChecked(true);
                break;
            case 2:
                if (imgData.get(position)!=1&&imgData.get(position)!=3)
                    vh.aSwitch.setChecked(false);
            default:
        }
        vh.aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                boasend(imgData.get(position), b);
            }
        });
        vh.aSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String data = vh.aSwitch.isChecked() ? "0" : "1";
                System.out.println(data);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        controlDevice("638233",tag[imgData.get(position)],data);
                        //airconditionControl();
                    }
                }).start();
            }
        });
//        vh.mText.setText(mData.get(position) + "");
        vh.nText.setText(nData.get(position) + "");
        vh.nText.setTextColor(0xff000000);
        vh.img.setImageResource(imgid[imgData.get(position)]);
        //设置item的点击事件
        //这里只设置了第一个item的，有需要的自己添加；
        vh.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<Integer> c1 = new ArrayList<>();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    c1.add(numMap.getOrDefault(0 + "x" +imgData.get(position) , 0));
                    c1.add(numMap.getOrDefault(1 + "x" + imgData.get(position) , 0));
                    c1.add(numMap.getOrDefault(2 + "x" +imgData.get(position)  , 0));
                }
                Intent intent1 = new Intent(context, Count.class);
                intent1.putIntegerArrayListExtra("name", (ArrayList<Integer>) c1);
                context.startActivity(intent1);

            }
        });
    }

    @Override
    public int getItemCount() {
        return nData.size();
    }

    public void add_dev(String name, int type) {
        if(typelist.contains(type)){}else{
            typelist.add(type);
            imgData.add(type);
            nData.add(name);
            notifyDataSetChanged();
        }
    }

    //初始化item布局文件的各个控件
    class VH extends RecyclerView.ViewHolder {
        TextView mText, nText;
        ImageView img;
        Switch aSwitch;

        public VH(@NonNull View itemView) {
            super(itemView);
            nText = itemView.findViewById(R.id.text1);
//            nText.setText("111");
            img = itemView.findViewById(R.id.img);
            aSwitch = itemView.findViewById(R.id.sw);
        }
    }


}
